import GameData_blxf from "../GameData/GameData";
import { VendorData_blxf } from "../GameData/VendorData";
import { CsvManager_blxf } from "../Manager/CsvManager";
import { EnumManager_blxf } from "../Manager/EnumManager";
import AudioModule_blxf from "../Module/AudioModule";
import { LoadModule_blxf } from "../Module/LoadModule";
import { NumModule_blxf } from "../Module/NumModule";
import PublicModule_blxf from "../Module/PublicModule";
import { UtilsModule_blxf } from "../Module/UtilsModule";
import GuestItem_blxf from "./guestItem";


/**
 * 游戏按钮名字
 */
enum GuestSpineNameType {
    /** 呼吸 */
    NAME_BREATH     = 'breath',
    /** 生气 */
    NAME_ANGRY      = 'angry',
    /** 开心 */
    NAME_HAPPY      = 'happy',
    /** 日常 */
    NAME_NORMAL     = 'idle',
}

/** 新年阶段 */
enum NewYearTimeType {
    NEW_START       = '2024/2/9',
    NEW_END         = '2024/2/17'
}

const smallPriceMsg: string = `送给孩子们的温暖，感谢您的善举&您的爱心，填满了孩子们的餐桌&感谢您，给留守儿童带来美味和关怀&您的慷慨，温暖了孩子们的心&爱心菜品，温暖留守儿童的每一天&您的善行，给孩子们带来希望和温暖`;


const guestPosXs = [ 75, 250, 425, 600 ];


// 三个客人、


const {ccclass, property} = cc._decorator;

/** 客人面板 */

@ccclass
export default class GuestPanel_blxf extends cc.Component {

    @property({ type: cc.Prefab, tooltip: '客人item' })
    guestItem: cc.Prefab = null;

    @property({ type: cc.Node, tooltip: '客人盒子' })
    guestBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '台词盒子' })
    dialogueBox: cc.Node = null;


    @property({ type: sp.Skeleton, tooltip: '客人动画' })
    guestSkeleton: sp.Skeleton = null;

    @property({ type: cc.Node, tooltip: '客人台词' })
    guestDialogueNode: cc.Node = null;

    @property({ type: cc.Sprite, tooltip: '客人图片' })
    guestImgSpr: cc.Sprite = null;

    @property({ type: cc.Node, tooltip: '收购台词' })
    guestDialogueNode2: cc.Node = null;



    @property({ tooltip: '出现概率' })
    loadGuestPercent: string = '70%';

    @property({ tooltip: '客人数据' })
    _guestData: any = null;

    @property({ tooltip: '商品数据' })
    _shopData: any = null;

    @property({ tooltip: '是否显示' })
    _isShow: boolean = false;

    @property({ tooltip: '日常台词倒计时' })
    _dialogueTimer: number = -1;

    @property({ tooltip: '日常台词间隔时间' })
    _normalTime: number = -1;

    @property({ tooltip: '隐藏倒计时' })
    _hideTimer: number = -1;

    @property({ tooltip: '台词类型' })
    _dialogueType: number = 1;

    @property({ tooltip: '台词动画' })
    _tween: cc.Tween = null;

    @property({ tooltip: '运行帧数' })
    _dtNum: number = 0;


    @property({ tooltip: '客人数据列表' })
    _guestThisList: GuestItem_blxf[] = [];

    @property({ tooltip: '已加载客人id列表' })
    _guestIdList: number[] = [];

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.initEvent_blxf();
    }

    initEvent_blxf () {
        cc.game.on('updateGuestShopData_blxf', this.updateShopData_blxf, this);
        cc.game.on('onPlayGuestAudio_blxf', this.onPlayGuestAudio_blxf, this);
        cc.game.on('onUpateGuestAnimation_blxf', this.onUpateGuestAnimation_blxf, this);
    }

    start () {
        this._normalTime = -1;
        this.loadGuestPercent = '70%';
        this.guestDialogueNode2.parent.zIndex = 2;

        let _isGui: boolean = GameData_blxf.instance.getIsGuidance_blxf();
        let _isRestart: boolean = PublicModule_blxf.isRestartGame;
        // if ( _isGui ) _isGui = !_isRestart;
        // /*_isGui &&*/ this.onCheckGuest_blxf( _isGui ? -1 : 10000, false, !_isGui );

        let _timeStr = NumModule_blxf.instance.getTimeStr_blxf();
        cc.warn('_timeStr >>', _timeStr, new Date( _timeStr ).getTime(), new Date( _timeStr.split('/').join('-') ).getTime() );

        // this.loadGuest_blxf( 1 );
        // this.loadGuest_blxf( 2 );
        // this.loadGuest_blxf( 3 );
    }

    update ( dt: number ) {
        let _isCheck: boolean = PublicModule_blxf.onCheckBundleType( 1 );
        if ( !_isCheck ) return;

        this._dtNum += 1;

        this._dtNum % 20 == 0 && this.onCheckLoadGuest( 1 );
        this._dtNum % 20 == 1 && this.onCheckLoadGuest( 2 );
        this._dtNum % 20 == 2 && this.onCheckLoadGuest( 3 );

        // if ( this._hideTimer > 0 ) {
        //     this._hideTimer -= dt;
        //     if ( this._hideTimer <= 0 ) {
        //         this.updateDialogueScale( false );
        //     }
        // } else {
        //     if ( this._normalTime > 0 ) {
        //         this._normalTime -= dt;
        //         if ( this._normalTime <= 0 ) {
        //             this.onNormalDialogue_blxf();
        //         }
        //     }
        // }

    }

    /** 检测加载客人 */
    onCheckLoadGuest ( guestId: number ) {
        let _isLoad: boolean = !!this.findGuestThis_blxf( guestId );
        if ( _isLoad ) return;

        let _targetId: number = guestId + 1;
        let _targetData: any = GameData_blxf.instance.getTargetData_blxf( _targetId );
        if ( !_targetData ) return;

        let _isCheck: boolean = this._guestIdList.includes( guestId );
        if ( _isCheck ) return;

        if ( this._guestIdList.length == 3 ) return;

        this._guestIdList.push( guestId );

        this.loadGuest_blxf( guestId );

        // this._guestIdList.length == 1 && this.scheduleOnce(()=>{
        //     cc.game.emit('onFirstCheckGuest_blxf');
        // }, 0.5)
    }

    /**
     * 加载客人
     * @param guestId 客人id
     */
    loadGuest_blxf ( guestId: number ) {
        let _x: number = -337.5 + guestPosXs[ guestId ];
        let _guestNode: cc.Node = LoadModule_blxf.instance.LoadNode_blxf({
            prefabNode: this.guestItem, parentNode: this.guestBox, position: cc.v3(_x, -100, 0)
        })
        if ( !_guestNode ) return;

        let _guestThis = _guestNode.getComponent( GuestItem_blxf );
        _guestThis.initData_blxf({ guestId, dialogueParentNode: this.dialogueBox, guestPanelThis: this });

        this._guestThisList.push( _guestThis );

        let _targetId: number = guestId + 1;
        let _targetData = VendorData_blxf.instance.findTargetData_blxf( _targetId );
        let _shopId: number = _targetData.getBuyShopId_blxf();
        _guestThis.onCheckGuest_blxf( _shopId, false, false );
    }

    findGuestThis_blxf ( checkGuestId: number ) {
        let _guestThis = this._guestThisList.find( item =>{
            return item.getGuestId_blxf() == checkGuestId;
        })

        return _guestThis;
    }

    /** 更新客人动画 */
    onUpateGuestAnimation_blxf ( dialogueType: string ) {
        this._guestThisList.forEach( guestItem =>{
            guestItem.onAnimation_blxf( dialogueType );
        })
    }

    // 更新客人动作、台词
    updateGuestDialogue_blxf ( targetId: number, shopId: number, isNewShopId: boolean = false, isInit: boolean = false ) {
        let _guestThis: GuestItem_blxf = this.findGuestThis_blxf( targetId - 1 );
        if ( !_guestThis ) return;

        _guestThis.onCheckGuest_blxf( shopId, isNewShopId, isInit );
    }

    /** 获取已加载客人id列表 */
    onGuestIds_blxf () {
        let _guestIds: number[] = [];

        this._guestThisList.forEach( guestItem =>{
            let _guestId: number = guestItem.getGuestDataId_blxf();
            _guestIds.push( _guestId );
        })

        return _guestIds;
    }
    
    onHideAllGuestDialogue_blxf () {
        this._guestThisList.forEach( guestItem =>{
            guestItem.onHideGuestDialogue_blxf();
        })
    }

    /** 日常台词 */
    onNormalDialogue_blxf () {
        let { DIALOGUE_NORMAL, DIALOGUE_NEW_YEAR } = EnumManager_blxf.guestDialogueType;
        let _isNewYear: boolean = this.isNewYear_blxf();
        this.loadGuestDialogue_blxf( 3, !_isNewYear ? DIALOGUE_NORMAL : DIALOGUE_NEW_YEAR );
    }

    /** 更新商品数据 */
    updateShopData_blxf ( shopId: number ) {
        this._shopData = VendorData_blxf.instance.findShopData_blxf( shopId );
    }

    /** 播放客人入场音效 */
    onPlayGuestAudio_blxf () {
        if ( !this._guestData ) return;
        
        let { DialogueAudioId } = this._guestData;
        if ( !DialogueAudioId ) return;
        AudioModule_blxf.instance.playAudio_blxf( DialogueAudioId );

        this.loadGuestDialogue_blxf();
    }

    /**
     * 检测是否加载客人
     * @param shopId 目标商品id
     */
    onCheckGuest_blxf ( shopId: number, isNewShopId: boolean = false, isInit: boolean = false ) {
        cc.log('onCheckGuest_blxf >11>', shopId, isNewShopId);
        this.updateShopData_blxf( shopId );

        let _cfgGuestList: any[] = VendorData_blxf.instance.getGuestInfo_blxf();
        let _guestData: any = _cfgGuestList.find( guestItem => guestItem.isUnlock && guestItem.LikeShopId == shopId );
        if ( !isInit && !_guestData ) return this.onRandomGuest();

        let _isLoad: boolean = isInit || isNewShopId || NumModule_blxf.instance.isChance_blxf( this.loadGuestPercent );
        if ( !_isLoad ) return this.onRandomGuest();

        if ( _guestData ) this._guestData = _guestData;

        this.updateGuestSkeleton_blxf();
    }

    /** 随机客人 */
    onRandomGuest () {
        let _newShopId: number = VendorData_blxf.instance.getNewShopId_blxf();
        let _unlockGuestList: any[] = GameData_blxf.instance.getGuestList_blxf();
        let _isMoreGuest: boolean = _unlockGuestList.length > 1;

        let { GuestId } = this._guestData || {};
        let _guestList: any[] = VendorData_blxf.instance.getGuestInfo_blxf();
        let _newGuestData: any = _guestList.find( guestItem => guestItem.isUnlock && guestItem.LikeShopId == _newShopId );
        let _newGuestId: number = _isMoreGuest && _newGuestData ? _newGuestData.GuestId : null;

        _guestList = _guestList.filter( item => {
            return item.isUnlock && (!_isMoreGuest || item.GuestId != GuestId) && (item.GuestId != _newGuestId);
        });
        _guestList.sort((a, b) => Math.random() - 0.5);

        cc.log('_guestList >>', _newGuestId, GuestId, _guestList);
        this._guestData = _guestList[0];

        this._guestData && this.updateGuestSkeleton_blxf( true );
    }

    /** 更新客人Spine动画 */
    updateGuestSkeleton_blxf ( isRandom: boolean = false ) {
        cc.log('onCheckGuest_blxf >22>', isRandom);
        let { SpineId, DialogueAudioId, AtlasName, ImgName } = this._guestData;
        this.updateSkeleton_blxf( SpineId );

        if ( PublicModule_blxf.isGuestAudio ) {
            isRandom = false;
            PublicModule_blxf.isGuestAudio = false;
        }

        !isRandom && AudioModule_blxf.instance.playAudio_blxf( DialogueAudioId );

        // let path: string = AtlasName, imgName: number = ImgName;
        // LoadModule_blxf.instance.LoadImg_blxf({
        //     path, imgName, imgSpr: this.guestImgSpr
        // })
    }

    /**
     * 更新动画
     */
    updateSkeleton_blxf ( SpineId: string ) {
        // let _spineData: any = CsvManager_blxf.instance.getSpineDataById_blxf( SpineId );
        // if ( !_spineData ) return UtilsModule_blxf.instance.Log_blxf(`查找动画数据失败 SpineId => ${SpineId}`, 2);

        // let { DirName, FileName, DefaultName } = _spineData;
        // let _spinePath: string = `${DirName}/${FileName}`;
        // LoadModule_blxf.instance.LoadSpine_blxf( _spinePath, this.guestSkeleton, ()=>{
        //     this.loadGuestDialogue_blxf();

        //     this.onUpdateAnimation_blxf();
        // })
    }

    /** 客人出现动画 */
    onUpdateAnimation_blxf () {
        let _node = this.guestSkeleton.node;
        _node.scale = 0.8;
        _node.opacity = 100;
        cc.tween( _node ).to(0.5, { scale: 1, opacity: 255 }).start();
    }

    /**
     * 加载台词
     * @param dailogueType 台词类型 
     */
    loadGuestDialogue_blxf ( targetId: number = 3, dialogueType: string = EnumManager_blxf.guestDialogueType.DIALOGUE_START, isAnimation: boolean = false  ) {
        let _guestThis: GuestItem_blxf = this.findGuestThis_blxf( targetId - 1 );
        if ( !_guestThis ) return;

        _guestThis.loadGuestDialogue_blxf( dialogueType, isAnimation );

        // // if ( !this._isShow ) return;

        // // 播放客人动画
        // this.onAnimation_blxf( dialogueType );
        
        // if ( isAnimation || !this._guestData ) return;

        // let _dialogueStr: string = this._guestData[ dialogueType ];
        // if ( !_dialogueStr ) {
        //     return UtilsModule_blxf.instance.Log_blxf(`未找到相关台词 talkType => ${dialogueType}`);
        // }

        // let _dialogueList: string[] = _dialogueStr.split('&');
        // _dialogueList.sort((a, b) => Math.random() - 0.5);

        // let _dialogueText: string = _dialogueList[ 0 ];

        // let { ShopName } = this._shopData || { ShopName: '' };
        // _dialogueText = _dialogueText.replace('【目标物品】', ShopName);

        // this.updateDialogueNode_blxf( _dialogueText );
    }

    /**
     * 播放台词对应动画
     * @param dialogueType 台词类型 
     */
    onAnimation_blxf ( dialogueType: string ) {
        let _animationName: string;
        let { DIALOGUE_OK, DIALOGUE_ANGRY, DIALOGUE_START, DIALOGUE_NORMAL, DIALOGUE_NEW_YEAR } = EnumManager_blxf.guestDialogueType;
        switch ( dialogueType ) {
            case DIALOGUE_OK       : _animationName = GuestSpineNameType.NAME_HAPPY; break;
            case DIALOGUE_ANGRY    : _animationName = GuestSpineNameType.NAME_ANGRY; break;
            case DIALOGUE_START    :
            case DIALOGUE_NORMAL   :
            case DIALOGUE_NEW_YEAR : _animationName = GuestSpineNameType.NAME_NORMAL; break;
            default                : _animationName = GuestSpineNameType.NAME_BREATH; break;
        }
        this.playAnimation_blxf( _animationName );
    }

    /**
     * 播放客人动画
     * @param animationName 动画名
     */
    playAnimation_blxf ( animationName: string ) {
        let isLoop: boolean = animationName == GuestSpineNameType.NAME_BREATH;
        // cc.log('playAnimation_blxf >>', isLoop, animationName);
        UtilsModule_blxf.instance.palyAnimation_blxf( this.guestSkeleton, { animationName, isLoop });

        if ( isLoop ) return;
        let _duration: number = this.getAnimationTime_blxf( animationName );
        this.scheduleOnce(()=>{
            this.playAnimation_blxf( GuestSpineNameType.NAME_BREATH );
        }, _duration)
    }

    /**
     * 获取动画时间
     * @param animationName 动画名
     */
    getAnimationTime_blxf ( animationName: string ) {
        let duration: number = NumModule_blxf.instance.onAnimationTime_blxf( this.guestSkeleton, animationName );
        return duration;
    }

    /**
     * 更新台词
     * @param msg 台词
     */
    updateDialogueNode_blxf ( msg: string, type: number = 1 ) {
        // let _isAlike: boolean = type == this._dialogueType;
        // !_isAlike && this.updateDialogueScale( false );

        // this._hideTimer = 2;
        // this._normalTime = -1;
        // this._dialogueType = type;
        // this.updateDialogueScale( true );

        // AudioModule_blxf.instance.playAudio_blxf( EnumManager_blxf.gameAudioType.AUDIO_DIALOGUE );

        // let _dialogueNode = this._dialogueType == 1 ? this.guestDialogueNode : this.guestDialogueNode2;
        // UtilsModule_blxf.instance.setText_blxf( _dialogueNode, msg );
    }

    /**
     * 更新节点
     * @param isShow 是否显示 
     */
    updateNode_blxf ( isShow: boolean = false ) {
        this._isShow = isShow;
        this.node.opacity = isShow ? 255 : 0;
        this.updateDialogueScale( isShow );
    }

    /**
     * 显隐动画
     * @param isShow 是否显示
     */
    updateDialogueScale ( isShow: boolean ) {
        // this._isShow = isShow;
        // let _isGuest: boolean = this._dialogueType == 1;
        // let _t: number = 0.3, _delayTime: number = (_isGuest || !isShow) ? 0 : 0.5, _scaleY: number = isShow ? 1 : 0;
        // let _dialogueBox: cc.Node = _isGuest ? this.guestDialogueNode.parent : this.guestDialogueNode2.parent;
        // cc.tween( _dialogueBox )
        // .delay( _delayTime )
        // .to( _t, { scaleY: _scaleY }, cc.easeSineInOut() )
        // .call(()=>{
        //     if ( !this._isShow ) this._normalTime = 10;
        // })
        // .start();
    }

    /** 检测是否处于新年阶段 */
    isNewYear_blxf () {
        let { NEW_START, NEW_END } = NewYearTimeType;
        let _startTime: number = new Date( NEW_START ).getTime();
        let _endTime: number = new Date( NEW_END ).getTime();
        let _nowTime: number = NumModule_blxf.instance.getTime_blxf();

        let _isGT: boolean = NumModule_blxf.instance.onCompareNum_blxf( _nowTime, _startTime );
        let _isLT: boolean = NumModule_blxf.instance.onCompareNum_blxf( _endTime, _nowTime );

        let _isNewYear: boolean = _isGT && _isLT;
        return _isNewYear;
    }

    // 加载低价回收台词
    loadSmallPriceDialogue_blxf () {
        let _dialogueList: string[] = smallPriceMsg.split('&');
        _dialogueList.sort((a, b) => Math.random() - 0.5);
        let _dialogueText: string = _dialogueList[ 0 ];
        this.updateDialogueNode_blxf( _dialogueText, 2 );
    }
    
}
